import asyncio
import os
import json
from metagpt.config2 import Config
from roles import ArticleManager


async def generate_article(topic_requirements: str, output_dir: str = "articles"):
    """生成文章并保存结果"""
    # 确保输出目录存在
    os.makedirs(output_dir, exist_ok=True)
    
    # 创建文章经理
    article_manager = ArticleManager()
    
    # 运行文章创作流程
    print(f"🚀 开始文章创作流程: '{topic_requirements}'")
    result = await article_manager.run(topic_requirements)
    
    # 为输出文件创建一个安全的文件名
    safe_filename = "".join(c if c.isalnum() or c in [' ', '_', '-'] else '_' for c in topic_requirements)
    safe_filename = safe_filename[:50]  # 限制长度
    
    # 保存分析结果
    with open(os.path.join(output_dir, f"{safe_filename}_analysis.json"), "w", encoding="utf-8") as f:
        json.dump(result["analysis"], f, ensure_ascii=False, indent=2)
    
    # 保存大纲
    with open(os.path.join(output_dir, f"{safe_filename}_outline.json"), "w", encoding="utf-8") as f:
        json.dump(result["outline"], f, ensure_ascii=False, indent=2)
    
    # 保存文章内容
    with open(os.path.join(output_dir, f"{safe_filename}_article.md"), "w", encoding="utf-8") as f:
        f.write(result["content"])
    
    # 保存审查结果
    with open(os.path.join(output_dir, f"{safe_filename}_review.json"), "w", encoding="utf-8") as f:
        json.dump(result["review"], f, ensure_ascii=False, indent=2)
    
    print(f"✅ 文章创作完成！文件已保存到 {output_dir} 目录")
    print(f"📄 文章内容已保存为: {os.path.join(output_dir, f'{safe_filename}_article.md')}")
    
    return result


def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="MetaGPT文章创作工具")
    parser.add_argument("topic", type=str, help="文章主题或需求")
    parser.add_argument("--output", "-o", type=str, default="articles", help="输出目录")
    args = parser.parse_args()
    
    # 配置MetaGPT - 修改配置加载方式
    config = Config.default()
    
    # 运行文章生成
    asyncio.run(generate_article(args.topic, args.output))


if __name__ == "__main__":
    main() 